from django.shortcuts import render
from django.apps import apps
from django.http import JsonResponse
from django.db.models import Model
from django.db import connection
from django.urls import path, re_path
from django.views.decorators.csrf import csrf_exempt
from utils.route.wrappers import json_post_checker, login_permission
from apCelery.celeryApp import app


@csrf_exempt
@json_post_checker({"appName": str, "modelName": str})
def model_info(request, data: dict):
    """
    获取django模型的信息
    :param request:
    :param data:
    :return:
    """
    _app, _model_name = data['appName'], data['modelName']
    try:
        tb: Model = apps.get_model(app_label=_app, model_name=_model_name)
    except LookupError as err:
        return JsonResponse({"code": 404, "message": f"{_app}.{_model_name} 不存在"})

    return JsonResponse({"code": 200, "message": "", "data": {
        "name": tb.__name__,
        "tableName": tb._meta.db_table,
        "fields": [x.name for x in tb._meta.fields],
    }})


@csrf_exempt
@login_permission()
@json_post_checker({"sql": str})
def sql_execute(request, data: dict):
    """
    直接以django连接账号执行sql语句
    :param request:
    :param data:
    :return:
    """
    with connection.cursor() as cursor:
        try:
            cursor.execute(data.get('sql'))
            result = cursor.fetchall()
            return JsonResponse({"code": 200, "message": None, "data": result})
        except Exception as err:
            # cursor.rollback()
            return JsonResponse({"code": 500, "message": err.__str__()})
        finally:
            # cursor.commit()
            pass


@csrf_exempt
@login_permission()
@json_post_checker({"taskName": str}, optional_keys={"args": list, "kwargs": dict})
def celery_sender(request, data: dict):
    task = app.send_task(data.get('taskName'), data.get('args'), data.get('kwargs'))
    return JsonResponse({"code": 200, "message": None, "data": task.id})


urlpatterns = [
    path('model/info/', model_info, name='model_info'),
    path('model/execute/', sql_execute, name='sql_execute'),
    path('celery/', celery_sender, name='celery_sender')
]
